package com.sdhs.paas.internet.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextHelper
{
  public static final String KEY_REQUEST = "_request_";
  public static final String KEY_RESPONSE = "_response_";
  public static final String KEY_SERVLET_CONTEXT = "_servletcontext_";
  public static final String KEY_REQUESTURI = "_requesturi_";
  private static OurContext context = new OurContext(null);

  public static Set keys()
  {
    return ((Map)context.get()).keySet();
  }

  public static Object get(Object key)
  {
    return ((Map)context.get()).get(key);
  }

  public static void put(Object key, Object value)
  {
    ((Map)context.get()).put(key, value);
  }

  public static void clear()
  {
    context.remove();
  }

  public static HttpServletRequest getRequest()
  {
    return (HttpServletRequest)get("_request_");
  }

  public static Locale getLocale()
  {
    if (getRequest() != null)
      return getRequest().getLocale();
    return Locale.getDefault();
  }

  public static HttpServletResponse getResponse()
  {
    return (HttpServletResponse)get("_response_");
  }

  public static ServletContext getServletContext()
  {
    return (ServletContext)get("_servletcontext_");
  }

  public static String getRequestURI()
  {
    return (String)get("_requesturi_");
  }

  public static void init(HttpServletRequest request, HttpServletResponse response, ServletContext sc)
  {
    put("_request_", request);
    put("_response_", response);
    put("_servletcontext_", sc);

    put("_requesturi_", request.getRequestURI());
  }

  public static OurContext getAllContextParameter()
  {
    return context;
  }

  public static void setContextParameter(String name, Object obj)
  {
    ((Map)context.get()).put(name, obj);
  }

  public static Object getContextParameter(String name)
  {
    return ((Map)context.get()).get(name);
  }

  public static void sendRedirect(String url)
    throws IOException
  {
    getResponse().sendRedirect(url);
  }

  public static void forward(String url)
    throws ServletException, IOException
  {
    getRequest().getRequestDispatcher(url).forward(getRequest(), getResponse());
  }

  private static class OurContext extends ThreadLocal<Map>
  {
	public OurContext(Object obj){}
	  
    protected Map initialValue()
    {
      return new HashMap();
    }
  }
}